package com.talkweb.securitycamera.data.hadoopDB;

import com.talkweb.securitycamera.common.interfaces.dataprocess.FileCallback;
import com.talkweb.securitycamera.data.bean.MediaEntity;
import ohos.app.Context;
import ohos.data.distributed.common.Entry;
import ohos.data.distributed.common.Query;
import ohos.data.distributed.common.Value;
import ohos.utils.zson.ZSONObject;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @version 1.0.1
 * @description:
 * @program: security-camera
 * @Author xiaozhijun
 * @Date 2021/1/29 9:44
 */
public class HadoopHelper implements IDbControl<MediaEntity> {

    /**
     * 本地分布式数据库
     */
    private LocalHadoopDb hadoopDb;

    public HadoopHelper(Context context, String storeId, FileCallback fileCallback) {
        hadoopDb = new LocalHadoopDb(context, storeId, fileCallback);
    }

    @Override
    public int insert(MediaEntity entity) {
        int result = 0;
        try {
            //转成Json字符串
            Entry entry = new Entry(entity.getKeyMd5(), Value.get(entity.toJson().getBytes(StandardCharsets.UTF_8)));
            ArrayList entrys = new ArrayList<Entry>();
            entrys.add(entry);
            if (hadoopDb != null && hadoopDb.getKvStore() != null) {
                hadoopDb.getKvStore().putBatch(entrys);
                result = 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    @Override
    public ArrayList<MediaEntity> query(Query query) {
        if (hadoopDb != null && hadoopDb.getKvStore() != null) {
            try {
                List<Entry> entrys = hadoopDb.getKvStore().getEntries(query);
                if (entrys != null) {
                    ArrayList<MediaEntity> list = new ArrayList<>();
                    entrys.forEach((item) -> {
                        MediaEntity entity = ZSONObject.stringToClass(item.getValue().getString(), MediaEntity.class);
                        list.add(entity);
                    });
                    return list;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    public boolean delete(MediaEntity entity) {
        boolean result = false;
        if (hadoopDb != null && hadoopDb.getKvStore() != null) {
            try {
                hadoopDb.getKvStore().delete(entity.getKeyMd5());
                result = true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    @Override
    public void deleteDb() {
        if (hadoopDb != null) {
            hadoopDb.delete();
        }
    }

    @Override
    public void closeDb() {
        if (hadoopDb != null) {
            hadoopDb.close();
        }
    }
}
